import network
from microWebSrv import MicroWebSrv
import utime
import json

# 全局变量定义
ap = None
mws = None


def createWiFi():
    global ap
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid='ESP_config', channel=5, authmode=network.AUTH_OPEN)
    ap.ifconfig(('192.168.123.1', '255.255.255.0', '192.168.123.1', '8.8.8.8'))
    while not ap.active():
        pass
    print('Network config:', ap.ifconfig())

def create_web_server():
    """
    创建并启动Web服务器。
    """
    def _httpHandlerPostConfig(httpClient, httpResponse):
        """
        处理WiFi配网表单提交。
        """
        formData = httpClient.ReadRequestPostedFormData()
        ssid = formData["ssid"]
        password = formData["password"]
        print('接收到的SSID:', ssid)
        print('接收到的密码:', password)

        print("尝试连接到WiFi网络...")
        apw = network.WLAN(network.STA_IF)
        apw.active(True)
        try:
            apw.connect(ssid, password)
        except OSError as e:
            print(e)
            
        ip = None 
        for i in range(20):
            print("connecting to wifi ", i)
            if apw.isconnected():
                print('Network config:', apw.ifconfig())
                ip = apw.ifconfig()[0]
                break 
            utime.sleep(1)
        
        if ip != None:
            config = dict(essid=ssid, password=password) # 创建字典
            with open('wifi_config.json','w') as f:
                f.write(json.dumps(config)) # 将字典序列化为json字符串,存入wifi_config.json
                
            response = """
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>WiFi 配置成功</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            text-align: center;
                            margin: 20px;
                        }
                    h1 {
                        color: #333;
                    }
                    p {
                        color: #666;
                        font-size: 18px;
                    }
                </style>
            </head>
            <body>
                <h1>WiFi 配置成功</h1>
                <p>设备将尝试连接到新的WiFi网络。</p>
            </body>
            </html>
            """
            httpResponse.WriteResponseOk(headers=None, contentType="text/html", contentCharset="UTF-8", content=response)
        
            utime.sleep(3)
            # 关闭Web服务器
            global mws
            mws.Stop()
            print("Web服务器已关闭")

            # 关闭WiFi热点
            global ap
            ap.active(False)
            print("WiFi热点已关闭")
            
        else:
            response = """
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>WiFi 配置失败</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        text-align: center;
                        margin: 20px;
                    }
                    h1 {
                        color: #333;
                    }
                    p {
                        color: #666;
                        font-size: 18px;
                    }
                </style>
            </head>
            <body>
                <h1>WiFi 配置失败</h1>
                <p>稍后请重新配置。</p>
                <script>
                    setTimeout(function() {{
                        history.back();
                    }}, 2000);
                </script>
            </body>
            </html>
            """
            httpResponse.WriteResponseOk(headers=None, contentType="text/html", contentCharset="UTF-8", content=response)
            
            
    def _acceptWebSocketCallback(webSocket, httpClient):
        """
        接受WebSocket连接的回调函数。
        """
        print('WebSocket连接已打开')
        webSocket.OnTextMessage = lambda webSocket, msg: _recvMsg(webSocket, msg)
        webSocket.OnBinaryMessage = None
        webSocket.OnClosed = lambda webSocket: _closed(webSocket)

    def _recvMsg(webSocket, msg):
        """
        接收WebSocket消息的回调函数。
        """
        print('接收到WebSocket消息: %s' % msg)
        webSocket.SendTextMessage('收到消息: %s' % msg)  # 发送响应消息

    def _closed(webSocket):
        """
        WebSocket连接关闭的回调函数。
        """
        print('WebSocket连接已关闭')

    # HTML页面内容
    htmlPage = """
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>WiFi 配置</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            background-color: #f0f0f0;
                            margin: 0;
                            padding: 0;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            height: 100vh;
                        }
                        .container {
                            background-color: #fff;
                            padding: 20px;
                            border-radius: 8px;
                            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                            width: 80vw;
                        }
                        h1 {
                            text-align: center;
                            color: #333;
                        }
                        form {
                            display: flex;
                            flex-direction: column;
                        }
                        label {
                            margin-bottom: 5px;
                            color: #666;
                        }
                        input[type="text"], input[type="password"], input[type="submit"] {
                            width: 100%;
                            padding: 10px;
                            margin-bottom: 15px;
                            border: 1px solid #ccc;
                            border-radius: 4px;
                            box-sizing: border-box;
                        }
                        input[type="submit"] {
                            background-color: #4CAF50;
                            color: white;
                            border: none;
                            cursor: pointer;
                        }
                        input[type="submit"]:hover {
                            background-color: #45a049;
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <h1>WiFi 配置</h1>
                        <form action="/config" method="post">
                            <label for="ssid">SSID:</label>
                            <input type="text" id="ssid" name="ssid" required>
                            <label for="password">密码:</label>
                            <input type="password" id="password" name="password" required>
                            <input type="submit" value="提交">
                        </form>
                    </div>
                </body>
                </html>
    """

    routeHandlers = [
        ("/", "GET", lambda httpClient, httpResponse: httpResponse.WriteResponseOk(headers=None, contentType="text/html", contentCharset="UTF-8", content=htmlPage)),
        ("/config", "POST", _httpHandlerPostConfig)
    ]

    global mws
    mws = MicroWebSrv(routeHandlers=routeHandlers)
    mws.MaxWebSocketRecvLen = 256  # 设置WebSocket最大接收长度
    mws.WebSocketThreaded = False  # 不为每个WebSocket连接创建新线程
    mws.AcceptWebSocketCallback = _acceptWebSocketCallback  # 设置WebSocket连接回调函数
    mws.Start(threaded=True)  # 启动Web服务器，使用线程模式



# 主程序
if __name__ == '__main__':
    createWiFi()  # 启动Wi-Fi热点
    create_web_server()  # 启动Web服务器